package com.mhkj.execute.plan.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.mhkj.base.fruitType.entity.FruitType;
import com.mhkj.base.fruitType.service.FruitTypeService;
import com.mhkj.base.templete.entity.PlanTempleteData;
import com.mhkj.common.util.ExportExcelUtils;
import com.mhkj.execute.feedback.entity.PlanFeedBack;
import com.mhkj.execute.feedback.service.PlanFeedBackService;
import com.mhkj.execute.plan.entity.PlanNodeFruitArchivesInfo;
import com.mhkj.execute.plan.entity.PlanNodeNew;
import com.mhkj.execute.plan.service.PlanNodeExecutionService;
import com.mhkj.execute.plan.service.PlanNodeNewService;
import com.mhkj.fruit.key.entity.KeyFruitArchives;
import com.mhkj.fruit.key.entity.KeyFruitArchivesDetailed;
import com.mhkj.fruit.key.service.KeyFruitArchivesDetailedService;
import com.mhkj.fruit.key.service.KeyFruitArchivesService;
import com.mhkj.revise.plan.entity.PlanNode;
import com.mhkj.revise.plan.service.PlanNodeService;
import com.mhkj.revise.professional.service.ProfessionalPlanNodeService;
import com.mics.core.common.componet.JsonHandler;
import com.mics.core.common.componet.Pagination;
import com.mics.core.common.componet.ResponseMessage;
import com.mics.core.system.base.controller.BaseController;
import com.mics.core.system.base.entity.FileEntity;
import com.mics.core.system.base.service.FileService;
import com.mics.core.system.organizational.bean.Employee;
import com.mics.core.system.organizational.service.OrgService;
import com.mics.core.system.rbac.service.DictionaryService;

/**
 * 月度工作计划执行
 * 
 * @author wk
 * @date 2018年8月12日
 * @version 1.0
 */
@Controller
@RequestMapping("/monthlyPlanExecution")
public class MonthlyPlanNodeExecutionController extends BaseController<PlanNode> {

	@Resource
	private PlanNodeExecutionService planNodeExecutionService;
	@Resource
	private PlanNodeNewService planNodeNewService;
	@Resource
	private PlanNodeService planNodeService;
	@Autowired
	private FileService fileService;
	@Autowired
	private PlanFeedBackService planFeedBackService;
	@Autowired
	private KeyFruitArchivesService keyFruitArchivesService;
	@Autowired
	private FruitTypeService fruitTypeService;
	@Resource
	private ProfessionalPlanNodeService professionalPlanNodeService;

	@Autowired
	private OrgService orgService;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private KeyFruitArchivesDetailedService keyFruitArchivesDetailedService;

	@Resource
	private JsonHandler jsonHandler;

	/**
	 * 月度工作计划
	 * 
	 * @param response
	 * @param planNode
	 * @param pageIndex
	 * @param pageSize
	 * @throws ParseException
	 */
	@RequestMapping("/listByPage")
	@ResponseBody
	public void listByPage(HttpServletResponse response, String nodeName, String yearMonth, String state, Long itemId,
			int pageIndex, int pageSize) throws ParseException {
		if (nodeName == null) {
			nodeName = "";
		}
		if (state == null) {
			state = "";
		}
		String firstDay;
		String lastDay;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if (yearMonth == null) {

			// 获取本月
			Calendar cal_1 = Calendar.getInstance();// 获取当前日期
			cal_1.add(Calendar.MONTH, 0);
			cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
			firstDay = format.format(cal_1.getTime());

			// 获取结束月份
			Calendar cale = Calendar.getInstance();
			if (cale.get(Calendar.DATE) >= 20) {// 大于20号 需要查询下月
				cale.add(Calendar.MONTH, 1);
			} else {
				cale.add(Calendar.MONTH, 0);
			}
			cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
			lastDay = format.format(cale.getTime());
		} else {
			Date formattime = new SimpleDateFormat("yyyy-MM").parse(yearMonth);

			firstDay = format.format(formattime.getTime());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(formattime);
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
			lastDay = format.format(calendar.getTime());
		}
		Pagination<PlanNode> pagination = planNodeExecutionService.monthlyPlanListByPage(nodeName, firstDay, lastDay,
				state, itemId, pageIndex, pageSize);

		jsonHandler.sendJsonString(response, true, "获取数据成功", pagination,
				new String[] { "id", "plan.name", "business.typeName", "plan.planType.value", "nodeName",
						"nodeProperty.value", "completeStandard", "rate", "state", "beginDate", "endDate", "postName",
						"remark", "fruitType", "completeDate", "aduitState", "riskState" },
				new String[] { "id", "planName", "businessName", "planTypeName", "nodeName", "nodePropertyName",
						"completeStandard", "rate", "state", "beginDate", "endDate", "postName", "remark", "fruitType",
						"completeDate", "aduitState", "riskState" });
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see 新增节点
	 */
	@RequestMapping("/save")
	@ResponseBody
	public ResponseMessage save(PlanNodeNew t) {
		int deadline = (int) ((t.getBeginDate().getTime() - t.getEndDate().getTime()) / (1000 * 3600 * 24));
		Employee employee = orgService.employeeInfo(t.getPostPerson());
		t.setSign("new");
		t.setPostId(employee.getRoleList().get(0).getId());
		t.setOfficeId(employee.getOffice().getId());
		t.setCompanyId(employee.getCompanyid());
		t.setDeadline(deadline + 1);
		String message = planNodeNewService.save(t);
		if (message != null) {
			return ResponseMessage.createMessage(true, t.getId() + "");
		} else {
			return ResponseMessage.createMessage(false, message);
		}
	}

	/**
	 * 节点完成填报
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping("/saveKeyFruitArchives")
	@ResponseBody
	public ResponseMessage saveKeyFruitArchives(String data) {
		Gson gson = new Gson();
		PlanNodeFruitArchivesInfo planNodeFruitArchivesInfo = gson.fromJson(data, PlanNodeFruitArchivesInfo.class);
		PlanNode planNodeInfo = planNodeFruitArchivesInfo.getPlanNode();
		PlanNode planNode1 = planNodeExecutionService.getById(planNodeInfo.getId());

		PlanFeedBack planFeed = new PlanFeedBack();// 节点计划填报

		List<PlanNode> planNodelist = professionalPlanNodeService.getSameNameNode(planNode1.getId());// 获取关键，主项，专项 节点数据

		for (PlanNode planNode : planNodelist) {
			PlanFeedBack planFeedBack = new PlanFeedBack();// 节点计划填报
			planFeedBack.setCurrentProgress(100);
			planFeedBack.setIsComplete(1);
			planFeedBack.setPlanNode(planNode);
			planFeedBack.setOverDate(planNodeInfo.getCompleteDate());
			planFeedBack.setCompleteIns(planNodeInfo.getRemark());

			planFeedBackService.save(planFeedBack);
			if (planNode.getPlan().getPlanType().getCode().equals("100044")
					|| planNode.getPlan().getPlanType().getCode().equals("100045")) {// 专项或者职能节点
				planFeed.setId(planFeedBack.getId());
			}

			PlanTempleteData planTempleteData = planNode1.getNodeTempleteDataId();

			KeyFruitArchives archives = new KeyFruitArchives();
			FruitType fruitType = fruitTypeService.getByNodeResult(planTempleteData.getId());
			archives.setFruitType(fruitType);
			archives.setKeyType(planNode.getPlan().getPlanType());
			archives.setPlanNode(planFeedBack.getPlanNode());
			archives.setPlanFeedBack(planFeedBack);
			keyFruitArchivesService.save(archives);

			List<KeyFruitArchivesDetailed> list = planNodeFruitArchivesInfo.getDetailinfos();// 成果档案明细
			for (KeyFruitArchivesDetailed keyFruitArchivesDetail1 : list) {
				KeyFruitArchivesDetailed keyFruitArchivesDetail = new KeyFruitArchivesDetailed();
				keyFruitArchivesDetail.setKeyFruitArchives(archives);
				keyFruitArchivesDetail.setAchievementNature(
						dictionaryService.getById(keyFruitArchivesDetail1.getAchievementNatureId()));
				keyFruitArchivesDetail.setAchievementName(keyFruitArchivesDetail1.getAchievementName());
				keyFruitArchivesDetail.setAchievementTime(keyFruitArchivesDetail1.getAchievementTime());
				keyFruitArchivesDetail.setStoragePlace(keyFruitArchivesDetail1.getStoragePlace());
				keyFruitArchivesDetail.setPatternManifestation(
						dictionaryService.getById(keyFruitArchivesDetail1.getPatternManifestationId()));
				keyFruitArchivesDetailedService.save(keyFruitArchivesDetail);
				// 获取变更后的施工方案名
				String fileName = keyFruitArchivesDetail1.getFileName();
				if (fileName != null && !fileName.isEmpty()) {
					String[] fileNameArr = fileName.split(";");
					// 获取变更后的施工方案名URL
					String fileUrl = keyFruitArchivesDetail1.getFileUrl();
					String[] fileUrlArr = fileUrl.split(";");

					// 循环插入数据库
					for (int i = 0; i < fileNameArr.length; i++) {
						FileEntity fileEntity = new FileEntity();
						fileEntity.setTableId(keyFruitArchivesDetail.getId());
						fileEntity.setTableName("t_key_fruit_archives_detailed");
						fileEntity.setFileName(fileNameArr[i]);
						fileEntity.setFileUrl(fileUrlArr[i]);
						fileService.save(fileEntity);
					}
				}
			}

			planNode.setAduitState(1);
			planNodeExecutionService.edit(planNode);
		}

		String message = planNodeExecutionService.edit(planNode1);
		if (message != null) {
			return ResponseMessage.createMessage(true, planFeed.getId() + "");
		} else {
			return ResponseMessage.createMessage(false, message);
		}
	}

	/**
	 * 查看节点详情
	 */
	@RequestMapping("/info")
	@ResponseBody
	public void info(HttpServletResponse response, long id) {
		PlanNode planNode = planNodeExecutionService.getById(id);
		if (!Strings.isNullOrEmpty(planNode.getOfficeId())) {
			planNode.setOfficeName(orgService.officeInfo(planNode.getOfficeId()).getName());
		}

		jsonHandler.sendJsonString(response, true, "获取数据成功", planNode,
				new String[] { "id", "plan.id", "plan.name", "business.typeName", "business.id", "plan.planType.value",
						"plan.planType.id", "nodeName", "nodeProperty.id", "nodeProperty.value", "deadlineDesc",
						"completeStandard", "rate", "overDay", "state", "beginDate", "endDate", "postName", "remark",
						"officeName" },
				new String[] { "id", "planId", "planName", "businessName", "business", "planTypeName", "planType",
						"nodeName", "nodeProperty", "nodePropertyName", "deadlineDesc", "completeStandard", "rate",
						"overDay", "state", "beginDate", "endDate", "postName", "remark", "officeName" });

	}

	/**
	 * 查看节点详情
	 */
	@RequestMapping("/newInfo")
	@ResponseBody
	public void newInfo(HttpServletResponse response, long id) {
		PlanNodeNew planNode = planNodeNewService.getById(id);
		if (!Strings.isNullOrEmpty(planNode.getPostPerson())) {
			planNode.setPostPersonName(orgService.employeeInfo(planNode.getPostPerson()).getName());
		}
		if (!Strings.isNullOrEmpty(planNode.getCooperatePostPerson())) {

			planNode.setCooperatePostPersonName(orgService.employeeInfo(planNode.getCooperatePostPerson()).getName());
		}
		jsonHandler.sendJsonString(response, true, "获取数据成功", planNode,
				new String[] { "id", "plan.id", "plan.name", "business.typeName", "business.id", "plan.planType.value",
						"plan.planType.id", "nodeName", "nodeProperty.id", "nodeProperty.value", "deadlineDesc",
						"completeStandard", "rate", "state", "beginDate", "endDate", "postPerson", "postName", "remark",
						"cooperatePostPerson", "cooperateBeginDate", "cooperateEndDate", "cooperateMatters",
						"cooperatePostPersonName", "postPersonName" },
				new String[] { "id", "planId", "planName", "businessName", "business", "planTypeName", "planType",
						"nodeName", "nodeProperty", "nodePropertyName", "deadlineDesc", "completeStandard", "rate",
						"state", "beginDate", "endDate", "postPerson", "postName", "remark", "cooperatePostPerson",
						"cooperateBeginDate", "cooperateEndDate", "cooperateMatters", "cooperatePostPersonName",
						"postPersonName" });

	}

	/**
	 * 节点计划成果明细
	 * 
	 * @param response
	 * @param planNode
	 * @param pageIndex
	 * @param pageSize
	 */
	@RequestMapping("/fruitArchivesDetailedListByPage")
	@ResponseBody
	public void fruitArchivesDetailedListByPage(HttpServletResponse response,
			KeyFruitArchivesDetailed keyFruitArchivesDetailed, int pageIndex, int pageSize) {

		Pagination<KeyFruitArchivesDetailed> pagination = keyFruitArchivesDetailedService
				.listByPage(keyFruitArchivesDetailed, pageIndex, pageSize);

		jsonHandler.sendJsonString(response, true, "获取数据成功", pagination,
				new String[] { "id", "achievementName", "achievementNature.value", "patternManifestation.value",
						"achievementTime", "storagePlace", "listFile" },
				new String[] { "id", "achievementName", "achievementNature", "patternManifestation", "achievementTime",
						"storagePlace", "listFile" });
	}

	@RequestMapping("/del")
	@ResponseBody
	public ResponseMessage del(PlanNodeNew t) {
		String message = planNodeNewService.del(t);
		return ResponseMessage.createMessage(true, message);
	}

	/**
	 * 月度工作计划 统计
	 * 
	 * @param response
	 * @param planNode
	 * @param pageIndex
	 * @param pageSize
	 */
	@RequestMapping("/workbenchCount")
	@ResponseBody
	public Map<String, Object> workbenchCount() {
		String firstDay;
		String lastDay;

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		// 获取本月
		Calendar cal_1 = Calendar.getInstance();// 获取当前日期
		cal_1.add(Calendar.MONTH, 0);
		cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		firstDay = format.format(cal_1.getTime());

		// 获取结束月份
		Calendar cale = Calendar.getInstance();
		if (cale.get(Calendar.DATE) >= 20) {// 大于20号 需要查询下月
			cale.add(Calendar.MONTH, 1);
		} else {
			cale.add(Calendar.MONTH, 0);
		}
		cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
		lastDay = format.format(cale.getTime());

		Map<String, Object> pagination = planNodeExecutionService.workbenchCount(firstDay, lastDay);

		return pagination;
	}

	/**
	 * 获取导出
	 * 
	 * @author
	 * @date 2018年5月22日
	 * @version 1.0
	 */
	@RequestMapping("/exportExcel")
	public Map<String, Object> exportExcel(HttpServletResponse response, String nodeName, String yearMonth,
			String state, Long itemId, int pageIndex, int pageSize) throws ParseException {
		if (nodeName == null) {
			nodeName = "";
		}
		if (state == null) {
			state = "";
		}
		String firstDay;
		String lastDay;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if (yearMonth == null) {

			// 获取本月
			Calendar cal_1 = Calendar.getInstance();// 获取当前日期
			cal_1.add(Calendar.MONTH, 0);
			cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
			firstDay = format.format(cal_1.getTime());

			// 获取结束月份
			Calendar cale = Calendar.getInstance();
			if (cale.get(Calendar.DATE) >= 20) {// 大于20号 需要查询下月
				cale.add(Calendar.MONTH, 1);
			} else {
				cale.add(Calendar.MONTH, 0);
			}
			cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
			lastDay = format.format(cale.getTime());
		} else {
			Date formattime = new SimpleDateFormat("yyyy-MM").parse(yearMonth);

			firstDay = format.format(formattime.getTime());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(formattime);
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
			lastDay = format.format(calendar.getTime());
		}
		Pagination<PlanNode> pagination = planNodeExecutionService.monthlyPlanListByPage(nodeName, firstDay, lastDay,
				state, itemId, pageIndex, pageSize);

		List<PlanNode> objList = pagination.getData();

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (objList != null && objList.size() > 0) {
			Map<String, Object> map = null;
			PlanNode bean = null;
			for (int i = 0, size = objList.size(); i < size; i++) {
				bean = objList.get(i);
				map = beanToMap(bean);
				map.put("planNodeName", objList.get(i).getPlan().getName());
				map.put("rate", objList.get(i).getRate() + "%");
				String aduitStateValue = "";
				String stateValue = "";
				if (objList.get(i).getAduitState() == 0) {
					aduitStateValue = "";
				} else if (objList.get(i).getAduitState() == 1) {
					aduitStateValue = "审批中";
				} else if (objList.get(i).getAduitState() == 2) {
					aduitStateValue = "通过";
				} else if (objList.get(i).getAduitState() == 3) {
					aduitStateValue = "未通过";
				}
				if (objList.get(i).getRiskState() == 1) {
					stateValue = "有风险";
				} else if (objList.get(i).getRiskState() == 2) {
					stateValue = "失控";
				} else {
					if (objList.get(i).getState() == 1) {
						stateValue = "未开始";
					} else if (objList.get(i).getState() == 2) {
						stateValue = "进行中";
					} else if (objList.get(i).getState() == 3) {
						stateValue = "有风险";
					} else if (objList.get(i).getState() == 4) {
						stateValue = "失控";
					} else if (objList.get(i).getState() == 5) {
						stateValue = "已完成";
					} else if (objList.get(i).getState() == 6) {
						stateValue = "延期完成";
					} else if (objList.get(i).getState() == 7) {
						stateValue = "逾期";
					} else if (objList.get(i).getState() == 8) {
						stateValue = "节点暂停";
					} else if (objList.get(i).getState() == 9) {
						stateValue = "节点取消";
					}
				}

				map.put("aduitState", aduitStateValue);
				map.put("state", stateValue);

				list.add(map);
			}
		}
		ExportExcelUtils excel = new ExportExcelUtils();
		String title = "编号,计划名称,节点名称,状态,进度,开始时间,结束时间,完成时间,成果状态";
		String key = "id,planNodeName,nodeName,state,rate,beginDate,endDate,completeDate,aduitState";
		excel.exportData(list, title, key, "月度工作计划信息", response);

		return null;
	}

	public static <T> Map<String, Object> beanToMap(T bean) {
		Map<String, Object> map = Maps.newHashMap();
		if (bean != null) {
			BeanMap beanMap = BeanMap.create(bean);
			for (Object key : beanMap.keySet()) {
				map.put(key + "", beanMap.get(key));
			}
		}
		return map;
	}
	
	
	/**
	 * 资料套打 资料清单
	 * 
	 * @param response
	 * @param planNode
	 * @param pageIndex
	 * @param pageSize
	 */
	@RequestMapping("/dataPrintInfo")
	@ResponseBody
	public List<Map<String, Object>> dataPrintInfo(Long planNodeId) {
		PlanNode node = planNodeExecutionService.getById(planNodeId);
		List<Map<String, Object>> list = planNodeExecutionService.dataPrintInfo(planNodeId);

		return list;
	}
	
	
}
